<script setup lang="ts">
import { TextValue, TTextValueSqlInfo } from '@/models/reactiveComponent';
import { computed, inject } from 'vue'
import { getReactData } from './utils';
import * as injectKeys from "@/services/injectKeys";


const datasetServices = inject(injectKeys.datasetKey)!
const sqlServices = inject(injectKeys.sqlAnalyzeKey)!
const dbServices = inject(injectKeys.dbKey)!



const props = defineProps<{ model: TextValue }>()
const model = props.model

const ctx = model.contexts.map(ct => {

    if (typeof ct === 'string') {
        return computed(() => ct)
    }

    const sqlInfo = ct as TTextValueSqlInfo

    const tables = sqlServices.getTableNames(sqlInfo.sql)

    return computed(() => {
        const data = getReactData(model.id, sqlInfo.sql, tables, {
            dataset: datasetServices,
            sqlAnalyze: sqlServices,
            db: dbServices,
        })

        if (data.value.rows.length === 0) {
            return null
        }

        return data.value.rows[0][data.value.fields[0]]
    })


})


</script>

<template>
    <div class="textValue-box" :data-tag="model.tag">
        <span v-for="ct in ctx">{{ ct.value }}</span>
    </div>
</template>

<style scoped></style>